<template>
  <div class="student-list-container">
    <el-card class="student-card">
      <template #header>
        <div class="card-header">
          <h3>学生名单管理</h3>
          <div class="header-actions">
            <el-button type="primary" @click="showAddStudentDialog">
              <el-icon><plus /></el-icon> 添加学生
            </el-button>
            <el-button type="success" @click="showImportDialog">
              <el-icon><upload /></el-icon> 导入Excel
            </el-button>
          </div>
        </div>
      </template>

      <!-- 学生列表 -->
      <div class="student-list">
        <el-table
          :data="filteredStudents"
          border
          style="width: 100%"
          v-loading="loading"
          height="500"
        >
          <el-table-column prop="studentId" label="学号" width="120" sortable />
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="grade" label="年级" width="100" sortable />
          <el-table-column prop="major" label="专业" />
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="scope">
              <el-button
                size="small"
                type="primary"
                @click="handleEdit(scope.row)"
                :icon="Edit"
                circle
              />
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row)"
                :icon="Delete"
                circle
              />
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalStudents"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 添加/编辑学生对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑学生信息' : '添加学生'"
      width="500px"
    >
      <el-form
        :model="studentForm"
        :rules="rules"
        ref="studentFormRef"
        label-width="80px"
      >
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="studentForm.studentId" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="studentForm.name" />
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-select v-model="studentForm.grade" placeholder="请选择年级" style="width: 100%">
            <el-option
              v-for="year in gradeOptions"
              :key="year"
              :label="year"
              :value="year"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-input v-model="studentForm.major" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 导入Excel对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="导入学生名单"
      width="500px"
    >
      <div class="import-container">
        <el-upload
          class="upload-excel"
          drag
          action="#"
          :auto-upload="false"
          :on-change="handleExcelChange"
          :file-list="fileList"
          accept=".xlsx, .xls"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            拖拽Excel文件到此处，或 <em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              请上传Excel文件，包含学号、姓名、年级、专业四列数据
            </div>
          </template>
        </el-upload>

        <div class="import-preview" v-if="previewData.length > 0">
          <h4>数据预览 (前5条)</h4>
          <el-table :data="previewData.slice(0, 5)" border style="width: 100%">
            <el-table-column prop="studentId" label="学号" width="120" />
            <el-table-column prop="name" label="姓名" width="120" />
            <el-table-column prop="grade" label="年级" width="100" />
            <el-table-column prop="major" label="专业" />
          </el-table>
          <div class="preview-info">
            共 {{ previewData.length }} 条数据
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="importStudents" :disabled="previewData.length === 0">
            导入
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Upload, UploadFilled } from '@element-plus/icons-vue'
import * as XLSX from 'xlsx'
import logger from '@/utils/Logger'

export default {
  name: 'StudentList',
  components: {
    Plus,
    Upload,
    UploadFilled
  },
  setup() {
    const store = useStore()
    const loading = ref(false)
    const dialogVisible = ref(false)
    const importDialogVisible = ref(false)
    const isEdit = ref(false)
    const studentFormRef = ref(null)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const fileList = ref([])
    const previewData = ref([])

    // 表单数据
    const studentForm = reactive({
      studentId: '',
      name: '',
      grade: '',
      major: ''
    })

    // 表单验证规则
    const rules = {
      studentId: [
        { required: true, message: '请输入学号', trigger: 'blur' },
        { pattern: /^\d{5,12}$/, message: '学号必须为5-12位数字', trigger: 'blur' }
      ],
      name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '姓名长度在2-20个字符之间', trigger: 'blur' }
      ],
      grade: [
        { required: true, message: '请选择年级', trigger: 'change' }
      ],
      major: [
        { required: true, message: '请输入专业', trigger: 'blur' }
      ]
    }

    // 计算属性
    const students = computed(() => store.state.students || [])
    const totalStudents = computed(() => students.value.length)
    const filteredStudents = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return students.value.slice(start, end)
    })

    // 年级选项（当前年份-10年 到 当前年份+1年）
    const currentYear = new Date().getFullYear()
    const gradeOptions = Array.from({ length: 12 }, (_, i) => (currentYear - 10 + i).toString())

    // 方法
    const loadStudents = async () => {
      loading.value = true
      try {
        await store.dispatch('fetchStudents')
        logger.info('学生数据加载成功')
      } catch (error) {
        logger.error('加载学生数据失败', error)
        ElMessage.error('加载学生数据失败')
      } finally {
        loading.value = false
      }
    }

    const showAddStudentDialog = () => {
      isEdit.value = false
      resetForm()
      dialogVisible.value = true
    }

    const showImportDialog = () => {
      fileList.value = []
      previewData.value = []
      importDialogVisible.value = true
    }

    const handleEdit = (row) => {
      isEdit.value = true
      Object.assign(studentForm, row)
      dialogVisible.value = true
    }

    const handleDelete = (row) => {
      ElMessageBox.confirm(
        `确定要删除学生 ${row.name} (${row.studentId}) 吗？`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(async () => {
          try {
            await store.dispatch('deleteStudent', row.studentId)
            ElMessage.success('删除成功')
            logger.info(`成功删除学生: ${row.name} (${row.studentId})`)
          } catch (error) {
            logger.error('删除学生失败', error)
            ElMessage.error('删除学生失败')
          }
        })
        .catch(() => {
          // 用户取消删除
        })
    }

    const resetForm = () => {
      studentForm.studentId = ''
      studentForm.name = ''
      studentForm.grade = ''
      studentForm.major = ''
      if (studentFormRef.value) {
        studentFormRef.value.resetFields()
      }
    }

    const submitForm = async () => {
      if (!studentFormRef.value) return

      await studentFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            if (isEdit.value) {
              await store.dispatch('updateStudent', { ...studentForm })
              ElMessage.success('更新成功')
              logger.info(`成功更新学生: ${studentForm.name} (${studentForm.studentId})`)
            } else {
              // 检查学号是否已存在
              const exists = students.value.some(s => s.studentId === studentForm.studentId)
              if (exists) {
                ElMessage.error('学号已存在')
                return
              }

              await store.dispatch('addStudent', { ...studentForm })
              ElMessage.success('添加成功')
              logger.info(`成功添加学生: ${studentForm.name} (${studentForm.studentId})`)
            }
            dialogVisible.value = false
          } catch (error) {
            logger.error('保存学生信息失败', error)
            ElMessage.error('保存失败')
          }
        }
      })
    }

    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
    }

    const handleExcelChange = (file) => {
      if (!file) return

      const reader = new FileReader()
      reader.onload = (e) => {
        try {
          const data = new Uint8Array(e.target.result)
          const workbook = XLSX.read(data, { type: 'array' })
          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]
          const jsonData = XLSX.utils.sheet_to_json(worksheet)

          // 验证和转换数据
          const validData = jsonData.map((item, index) => {
            // 检查必要字段
            if (!item['学号'] || !item['姓名'] || !item['年级'] || !item['专业']) {
              logger.warn(`第 ${index + 2} 行数据缺少必要字段`)
              return null
            }

            return {
              studentId: String(item['学号']),
              name: String(item['姓名']),
              grade: String(item['年级']),
              major: String(item['专业'])
            }
          }).filter(item => item !== null)

          previewData.value = validData
          logger.info(`Excel解析成功，共 ${validData.length} 条有效数据`)
        } catch (error) {
          logger.error('解析Excel文件失败', error)
          ElMessage.error('解析Excel文件失败，请检查文件格式')
          previewData.value = []
        }
      }
      reader.readAsArrayBuffer(file.raw)
    }

    const importStudents = async () => {
      if (previewData.value.length === 0) {
        ElMessage.warning('没有可导入的数据')
        return
      }

      try {
        loading.value = true

        // 检查重复学号
        const existingIds = new Set(students.value.map(s => s.studentId))
        const newStudents = []
        const duplicates = []

        previewData.value.forEach(student => {
          if (existingIds.has(student.studentId)) {
            duplicates.push(student)
          } else {
            newStudents.push(student)
            existingIds.add(student.studentId) // 防止导入数据中有重复
          }
        })

        if (duplicates.length > 0) {
          logger.warn(`发现 ${duplicates.length} 个重复学号，将被跳过`)
          ElMessage.warning(`发现 ${duplicates.length} 个重复学号，将被跳过`)
        }

        if (newStudents.length > 0) {
          await store.dispatch('importStudents', newStudents)
          ElMessage.success(`成功导入 ${newStudents.length} 名学生`)
          logger.info(`成功导入 ${newStudents.length} 名学生`)
          importDialogVisible.value = false
        } else {
          ElMessage.warning('没有新的学生数据可导入')
        }
      } catch (error) {
        logger.error('导入学生失败', error)
        ElMessage.error('导入学生失败')
      } finally {
        loading.value = false
      }
    }

    onMounted(() => {
      loadStudents()
    })

    return {
      loading,
      students,
      filteredStudents,
      totalStudents,
      currentPage,
      pageSize,
      dialogVisible,
      importDialogVisible,
      isEdit,
      studentForm,
      studentFormRef,
      rules,
      gradeOptions,
      fileList,
      previewData,
      Edit,
      Delete,
      showAddStudentDialog,
      showImportDialog,
      handleEdit,
      handleDelete,
      submitForm,
      handleSizeChange,
      handleCurrentChange,
      handleExcelChange,
      importStudents
    }
  }
}
</script>

<style scoped>
.student-list-container {
  width: 100%;
}

.student-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.import-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.import-preview {
  margin-top: 20px;
}

.import-preview h4 {
  margin-top: 0;
  margin-bottom: 10px;
}

.preview-info {
  margin-top: 10px;
  text-align: right;
  color: #606266;
  font-size: 14px;
}

.upload-excel {
  width: 100%;
}
</style>
